<template>
  <div class="container">
    <div class="container_page">
      <page-header :title="$t('order_paymentDetail')"></page-header>
      <template v-if="info">
        <div class="box page_body">
          <div class="detail_card">
            <div class="title">{{ $t('order_paymentDetails2') }}</div>
            <div class="list_box">
              <div class="item">
                <div class="key">{{ $t('pay_category') }}</div>
                <div class="value">{{ $t(payStatusMap[info.type].label) }}</div>
              </div>

              <div class="item">
                <div class="key">{{ $t('pay_paymentStus') }}</div>
                <div class="value">
                  {{ $t(getOrderStatus(info.type, info)) }}
                </div>
              </div>
              <div class="item">
                <div class="key">{{ $t('pay_transactionNo') }}</div>
                <div class="value">{{ info.transferNo | stateFormats }}</div>
              </div>
              <div class="item">
                <div class="key">{{ $t('order_orderID') }}</div>
                <div class="value">{{ info.orderNo | stateFormats }}</div>
              </div>
              <div class="item">
                <div class="key">{{ $t('order_paymentMethod') }}</div>
                <div class="value">
                  {{ getPayMethod(info.paymentMethod, info) }}
                </div>
              </div>
              <div class="item">
                <div class="key">{{ $t('pay_paymentDate') }}</div>
                <div class="value">{{ info.createTime | dateformat }}</div>
              </div>

              <div class="item" v-if="info.refund">
                <div class="key">{{ $t('pay_refundAmount') }}</div>
                <div class="value payment">
                  {{
                    getRefund(info.type, info)
                      | amountFormats($currencyVal.symbol)
                  }}
                </div>
              </div>
              <div class="item">
                <div class="key">{{ $t('order_paymentAmount') }}</div>
                <div class="value payment">
                  {{
                    getAmount(info.type, info)
                      | amountFormats($currencyVal.symbol)
                  }}
                </div>
              </div>
            </div>
          </div>
          <!-- Billing rules  -->
          <div
            class="detail_card"
            v-if="info.billing && [1, 7].includes(info.type)"
          >
            <div class="title">{{ $t('order_pricePlan') }}</div>
            <div class="list_box billing">
              <div class="item">
                <div class="key">{{ $t('order_pricePlan') }}</div>
                <div class="value" v-if="info.billing.isSystem">
                  {{ $t('FREE_USAGE') }}
                </div>
                <div class="value" style="text-align: left;" v-else>
                  <span v-if="info.billing.freeDuration">{{
                    $t('billingRules1')
                      .replace(
                        '$order',
                        info.billing.freeLimit > 0
                          ? $t(`First_order${info.billing.freeLimit}`)
                          : $t('Every_order')
                      )
                      .replace('$freeDuration', info.billing.freeDuration)
                      .replace(
                        '$times1',
                        info.billing.freeDurationControlType == 1
                          ? info.billing.freeDuration > 1
                            ? $t('minute3')
                            : $t('minute2')
                          : info.billing.freeDurationControlType == 2
                          ? info.billing.freeDuration > 1
                            ? $t('hour4')
                            : $t('hour3')
                          : info.billing.freeDuration > 1
                          ? $t('days')
                          : $t('day')
                      )
                  }}</span>
                  <span
                    >{{
                      $t('billingRules2')
                        .replace(
                          '$thereafter',
                          info.billing.freeDuration ? $t('thereafter') : ''
                        )
                        .replace(/\s+$/, '')
                        .replace('$amount', formatMoney(info.billing.amount))
                        .replace('$cycle', info.billing.cycle)
                        .replace(
                          '$times2',
                          info.billing.controlType == 1
                            ? info.billing.cycle > 1
                              ? $t('minute3')
                              : $t('minute2')
                            : info.billing.controlType == 2
                            ? info.billing.cycle > 1
                              ? $t('hour4')
                              : $t('hour3')
                            : info.billing.cycle > 1
                            ? $t('days')
                            : $t('day')
                        )
                    }}{{
                      info.billing.dayAmount
                        ? $t('punctuation1')
                        : $t('punctuation2')
                    }}
                  </span>
                  <span v-if="info.billing.dayAmount">{{
                    $t('billingRules3').replace(
                      '$dayAmount',
                      formatMoney(info.billing.dayAmount)
                    )
                  }}</span>
                  <span v-if="info.billing.penaltyAmount">{{
                    $t('billingRules4')
                      .replace(
                        '$penaltyAmount',
                        formatMoney(info.billing.penaltyAmount)
                      )
                      .replace('$maxRentDuration', info.billing.maxRentDuration)
                      .replace(
                        '$times3',
                        info.billing.maxDurationControlType == 1
                          ? info.billing.maxRentDuration > 1
                            ? $t('minute3')
                            : $t('minute2')
                          : info.billing.maxDurationControlType == 2
                          ? info.billing.maxRentDuration > 1
                            ? $t('hour4')
                            : $t('hour3')
                          : info.billing.maxRentDuration > 1
                          ? $t('days')
                          : $t('day')
                      )
                  }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <bottom-button
          v-if="
            (!info.refund && !info.receiptUrl) ||
              (!info.receiptUrl &&
                (info.paymentState == 1 || info.paymentState == 3))
          "
          :title="$t('pay_getReceipt')"
          @click="showReceiptDialog"
          background="var(--page-bg)"
        ></bottom-button>
      </template>
      <template v-else>
        <div class="page_body">
          <empty-data orderType></empty-data>
        </div>
      </template>
      <!-- 邮箱 -->
      <van-dialog v-model="isShowEmailDialog" :showConfirmButton="false">
        <el-form
          :model="ruleForm"
          :rules="emailRules"
          ref="eamilFormRef"
          label-position="top"
          class="el_form"
        >
          <div class="title">{{ $t('pay_emailReceiptText') }}</div>
          <el-form-item prop="receiptEmail">
            <el-input
              v-model="ruleForm.receiptEmail"
              type="email"
              :placeholder="$t('toast_requiredEmail')"
              clearable
            >
            </el-input>
          </el-form-item>
          <div class="btns">
            <div class="btn flex_center" @click="isShowEmailDialog = false">
              {{ $t('profile_cancel') }}
            </div>
            <div class="btn flex_center" @click="submitForm('eamilFormRef')">
              {{ $t('home_confirm') }}
            </div>
          </div>
        </el-form>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import $api from '@/assets/js/api/index'
import share from '@/mixins/share'
export default {
  mixins: [share],
  data () {
    const validateEmail = (rule, value, callback) => {
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
      if (!value) {
        return callback(new Error(this.$t('toast_requiredEmail')))
      }
      setTimeout(() => {
        if (emailReg.test(value)) {
          callback()
        } else {
          callback(new Error(this.$t('toast_validEmail')))
        }
      }, 100)
    }
    return {
      payStatusMap: {
        1: {
          label: 'pay_rental', //租借
          isRefund: false
        },
        2: {
          label: 'pay_rental', //租借
          isRefund: true
        },
        5: {
          label: 'wallet_deposit', //押金
          isRefund: false
        },
        6: {
          label: 'wallet_deposit', //押金
          isRefund: true
        },
        7: {
          label: 'pay_powerbank', //罚金
          isRefund: false
        },
        8: {
          label: 'pay_powerbank', //罚金
          isRefund: true
        }
      },
      payMethodMap: {
        1: 'wallet_type_bankcard',
        3: 'wallet_type_applepay',
        4: 'wallet_type_googlepay'
      },
      orderStatusMap: {
        0: 'order_pendingPayment',
        1: 'order_paid',
        2: 'Order_Free_order',
        3: 'Payment_partialRefunded',
        4: 'pay_refuned'
      },
      info: null,
      isShowEmailDialog: false,
      ruleForm: {
        receiptEmail: ''
      },
      emailRules: {
        receiptEmail: [{ validator: validateEmail, trigger: 'blur' }]
      },
      userInfo: null
    }
  },
  created () {
    this.getLang()
  },
  methods: {
    getAmount (type, item) {
      if (![1, 2].includes(type)) {
        return Math.abs(item.amount)
      }
      return item.realAmount
    },
    getRefund (type, item) {
      // if (![1, 2].includes(type)) {
      //   return Math.abs(item.amount);
      // }
      return Math.abs(item.refundAmount)
    },
    getOrderStatus (type, item) {
      if (![1, 2].includes(type)) {
        return item.refund ? 'pay_refuned' : 'order_paid'
      }
      return this.orderStatusMap[item.paymentState]
    },
    getPayMethod (type, item) {
      let res = this.$t(this.payMethodMap[type])
      return type == 1 ? (item.bankNo ? res + `(${item.bankNo})` : res) : res
    },
    showReceiptDialog () {
      this.isShowEmailDialog = true
      this.ruleForm.receiptEmail = this.userInfo.receiptEmail
    },
    getUserInfo () {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      if (!userInfo) this.$router.replace('/login')
      this.userInfo = userInfo
    },

    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = {
            id: this.info.id,
            orderNo: this.info.orderNo,
            receiptEmail: this.ruleForm.receiptEmail
          }
          $api.user.sentStripeEmail(params).then(res => {
            if (res.code != '0') {
              this.global.toast(res.message)
              return
            }
            this.userInfo.receiptEmail = this.ruleForm.receiptEmail
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo));            
            location.reload()
            this.global.toast(res.message)
            this.isShowEmailDialog = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },
  mounted () {
    // let transferNo = this.$route.query.transferNo;
    // $api.user.getTransferDetails({ transferNo }).then(res => {
    //   if (res.code != "0") {
    //     this.global.toast(res.message);
    //     return;
    //   }
    //   this.info = res.data;
    // });
    this.info = JSON.parse(localStorage.getItem('pay_detail'))
    this.getUserInfo()
  },
  computed: {}
}
</script>
<style scoped lang="scss">
.container {
  background-color: var(--page-bg);
}
.container_page {
  --page-header-height: 44px;
  margin: 0;
  background-color: var(--page-bg);
  width: 100%;
  flex: 1;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.page_body {
  height: calc(100vh - var(--page-header-height));
  box-sizing: border-box;
  padding-bottom: 100px;
  background-color: var(--page-bg);
  overflow: auto;
}
.box {
  padding-bottom: 106px;
}
.action {
  position: fixed;
  width: 100%;
  height: 106px;
  bottom: 0;
  padding: 10px var(--gap);
  box-sizing: border-box;
  background-color: #ffffff;
}
.pay_type {
  padding: var(--gap);
  padding-bottom: 20px;
  .brief {
    font-size: 12px;
    font-weight: 500;
    color: #66666b;
    margin-left: 12px;
    margin-bottom: 8px;
  }
  .brief:nth-last-child(1) {
    margin-bottom: 0;
  }
}
.detail_card {
  padding: var(--gap);
  padding-bottom: 0px;
  .title {
    height: 20px;
    font-size: 17px;
    font-weight: 600;
    color: #39404d;
    margin-left: 10px;
    margin-bottom: 10px;
  }
  .list_box {
    background-color: var(--card-bg);
    padding-left: 20px;
    border-radius: 10px;
  }
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 0;
    border-top: 1px #e4e4e6 solid;

    &:first-child {
      border: none;
    }
    .key {
      font-size: 13px;
      font-weight: 500;
      text-align: left;
      color: #66666b;
      display: flex;
      align-items: center;
      .label {
        transform: translateY(1px);
      }
      img {
        width: 14px;
        height: 14px;
        margin-right: 6px;
      }
    }
    .value {
      font-size: 15px;
      color: #39404d;
      font-weight: 600;
      padding-right: 20px;
      text-align: right;
      &.payment {
        font-size: 20px;
        font-weight: Bold;
      }
    }
  }

  .billing .item {
    flex-direction: column;
    align-items: flex-start;
    .key {
      font-size: 15px;
      font-weight: 600;
      color: #39404d;
      margin-bottom: 4px;
    }
    .value {
      font-size: 13px;
      font-weight: 400;
      color: #66666b;
    }
  }
}

// 弹框
.van-dialog {
  .title {
    font-size: 15px;
  }
}
</style>
